package com.bawei.day20230109.base;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author 11295 刘铠源
 * 2023/1/9 10:12
 * @类名 BaseFragment
 */
public abstract class BaseFragment<vm extends BaseViewModel,DBD extends ViewDataBinding> extends Fragment {
    public vm viewmodel;
    public DBD databinding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        databinding = DataBindingUtil.inflate(inflater, layoutId(), container, false);
        databinding.setLifecycleOwner(this);
        return databinding.getRoot();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        init();
        initData();
    }

    protected abstract void initData();

    private void init() {
        if (viewmodel==null){
            Class cla=null;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType){
                cla=(Class)((ParameterizedType)type).getActualTypeArguments()[0];
            }else {
                cla=getClass();
            }
            viewmodel=(vm) ViewModelProviders.of(this).get(cla);
        }
    }

    protected abstract int layoutId();
}
